import {
  Button,
  Modal,
  Form,
  DatePicker,
  Switch,
  Radio,
  InputNumber,
  message,
} from 'antd'
import React, { useEffect, useRef, useState } from 'react'
import type { DatePickerProps, RadioChangeEvent } from 'antd'
// antd图标
import { HighlightOutlined, FormOutlined } from '@ant-design/icons'
import TextArea from 'antd/lib/input/TextArea'
import { useDispatch } from 'react-redux'
import {
  addBillData,
  changeBillData,
} from '../../../../../../store/action/billData'
// 导入时间处理
import moment from 'moment'

const Popup: any = (props: any) => {
  const [visible, setVisible] = useState(false)
  const [confirmLoading, setConfirmLoading] = useState(false)
  const [modalText, setModalText] = useState('Content of the modal')
  const dispatch = useDispatch()
  const formRef: any = useRef()
  // 类别
  let leiBie = ['早餐', '电子', '工资', '理财', '衣物', '其他']

  // 数据回填
  const [form] = Form.useForm()
  const [htKey, setHtKey] = useState(new Date().getTime())
  const showModal = (e: any) => {
    if (props.alter === 'alter') {
      // 处理数据
      // 处理时间格式
      let date: string = JSON.stringify(
        e.date.substr(0, 4) +
          '-' +
          e.date.substr(5, 2) +
          '-' +
          e.date.substr(8, 2)
      )
      setFormDate(e.date)
      setHtKey(e.key)
      let day = moment(date) //时间回显需要创建moment对象
      let moneyX: any = e.money
      if (e.money < 0) {
        moneyX = -e.money
      }
      const data = {
        money: e.money + '',
        date: day,
        sort: leiBie.indexOf(e.sort),
        notes: e.notes,
      }
      form.setFieldsValue(data)
    }
    setVisible(true)
  }

  const handleOk = () => {
    setModalText('The modal will be closed after two seconds')
    setConfirmLoading(true)
    setTimeout(() => {
      setVisible(false)
      setConfirmLoading(false)
    }, 2000)
  }

  const handleCancel = () => {
    setVisible(false)
  }

  // 获取时间
  const [formDate, setFormDate] = useState('')
  const onChangeDate: DatePickerProps['onChange'] = (date, dateString) => {
    let datax: any = dateString
    datax =
      datax.substr(0, 4) +
      '年' +
      datax.substr(5, 2) +
      '月' +
      datax.substr(8, 2) +
      '日'
    setFormDate(datax)
  }

  // 提交表单
  const onFinish = (values: any) => {
    // 处理表单数据结构
    // 如果是通过记一笔进来的 则money为负数
    let moneyX = -values.money
    // 如果是通过修改进来的 则money不变
    if (props.alter === 'alter') {
      moneyX = values.money
    }
    let data = {
      key: htKey,
      date: formDate,
      money: moneyX,
      sort: leiBie[values.sort],
      notes: values.notes ? values.notes : '无',
    }
    if (props.alter === 'alter') {
      dispatch(changeBillData(data) as any)
    } else {
      // 存储到本地
      dispatch(addBillData(data) as any)
    }

    // 用户提示
    message.success(props.alter === 'alter' ? '修改成功!' : '添加成功!')
    // 关闭窗口
    setVisible(false)
    // 清空表单
    formRef.current.resetFields()
  }

  const onFinishFailed = (errorInfo: any) => {
    // console.log('Failed:', errorInfo)
  }

  // 分类的value
  const [typeValue, setTypeValue] = useState(1)
  const onChangeType = (e: RadioChangeEvent) => {
    setTypeValue(e.target.value)
  }

  // 是否显示分类
  const [showSort, setShowSort] = useState(true)

  return (
    <div className="Popup">
      {props.alter === 'alter' ? (
        <Button
          type="primary"
          onClick={() => {
            showModal(props.data)
          }}>
          修改 <FormOutlined />
        </Button>
      ) : (
        <Button type="primary" onClick={showModal} style={props?.style}>
          记一笔 <HighlightOutlined />
        </Button>
      )}

      <Modal
        title={props.alter === 'alter' ? '正在修改' : '记一笔'}
        footer={null}
        visible={visible}
        onOk={handleOk}
        confirmLoading={confirmLoading}
        onCancel={handleCancel}>
        <Form
          form={form}
          ref={formRef}
          name="jiZhang"
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off">
          <Form.Item
            label="金额"
            name="money"
            hasFeedback
            rules={[
              { required: true, message: '请输入金额' },
              {
                pattern: /^[-,\d]\d+$/,
                message: '请输入正确的金额',
                validateTrigger: 'onChange',
              },
            ]}>
            <InputNumber style={{ width: '300px' }} placeholder="请输入金额" />
          </Form.Item>

          {/* 日期 */}
          <Form.Item
            label="日期"
            name="date"
            hasFeedback
            rules={[{ required: true, message: '请选择日期!' }]}>
            <DatePicker
              placeholder="选择日期"
              style={{ width: '10vw' }}
              onChange={onChangeDate}
            />
          </Form.Item>

          {/* 类型 */}
          <Form.Item
            label="类型"
            valuePropName="checked"
            style={{ margin: '0 0 20px 12px' }}>
            <Switch
              defaultChecked
              onChange={(e) => {
                setShowSort(e)
              }}
            />
            　 支出
            <div style={{ color: 'red' }}>
              {' '}
              {showSort ? '' : '请勾选类型选项!'}
            </div>
          </Form.Item>

          {/* 分类 */}
          <Form.Item
            label="分类"
            name="sort"
            style={{ display: showSort ? '' : 'none' }}
            rules={[{ required: true, message: '请选择分类!' }]}>
            <Radio.Group onChange={onChangeType} value={typeValue}>
              {leiBie.map((item, index) => {
                return (
                  <Radio
                    key={index}
                    value={index}
                    style={{
                      width: '150px',
                      height: '50px',
                      margin: '5px 0 0 0',
                    }}>
                    {item}
                  </Radio>
                )
              })}
            </Radio.Group>
          </Form.Item>

          {/* 备注 */}
          <Form.Item
            label="备注"
            name="notes"
            style={{ margin: '0 0 20px 12px' }}>
            <TextArea placeholder="请输入内容" rows={4} maxLength={200} />
          </Form.Item>
          <Form.Item>
            <Button
              style={{ margin: '0 20px 0 55px' }}
              type="primary"
              htmlType="submit"
              disabled={!showSort}>
              {props.alter === 'alter' ? '确认修改' : '记一笔'}
            </Button>
            <Button type="dashed" onClick={handleCancel}>
              取消
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}
export default Popup
